$(document).ready(function(){
//将为空数据项置0
	var prices = $(".price");
	for(var i=0;i<prices.length;i++){
		if(isEmpty(prices[i].value))
			prices[i].value = 0;
	}
	var stock_nums = $(".stock_num");
	for(var i=0;i<stock_nums.length;i++){
		if(isEmpty(stock_nums[i].innerHTML))
			stock_nums[i].innerHTML = 0;
	}
	isEmpty($("#goodsprice").val())?$("#goodsprice").val(0):"";
	isEmpty($("#takeprice").val())?$("#takeprice").val(0):"";
	isEmpty($("#othermoney").val())?$("#othermoney").val(0):"";
	isEmpty($("#allmoney").val())?$("#allmoney").val(0):"";

	$("#p_search").click(function(){
		if(!isEmpty($("#psearch_key").val())){
			$("#search_rs").remove();
			$.post("/purchase/ajaxbutton/", { "op": "getStockSInfo","val":$("#psearch_key").val(),"t":Math.random()},function(data){
				$("#hidden_data").val(data);
				data = eval(data);
				var rs_str = '<table border="0" id="search_rs" cellpadding="5px"><tr><td colspan="9"><a href="#">[关闭-搜索结果]</a></td></tr><tr class="thead"><td><span id=btn1><font color=red>全选</font></span></td><td width=150>中文名</td><td>采购点</td><td>商品SKU</td><td>图片</td><td>库存</td></tr>';
				for(var i=0;i<data.length;i++){
					
					 var datastock = data[i].storage;
					   var stocktmp = "";
                    if (datastock.length > 0) {
                        stocktmp += '<div class="newstocklist">';
                        for (var s = 0; s < datastock.length; s++) {
                            stocktmp += "<ul><li><font color=\"red\">" + datastock[s].stock + "</font></li><li>" + datastock[s].storage_name + "</li> <li>" + datastock[s].positions + "</li></ul>";
                        }
                        stocktmp += "</div>";
                    }
					rs_str += '<tr><td><input type="checkbox" value="'+i+'"></td><td>'+data[i].goods_name+'</td><td>'+data[i].businessman+'</td><td>'+data[i].goods_sku+'</td><td><img src="'+data[i].imagesurl+'" /></td><td>'+stocktmp+'</td>';
				}
				rs_str += '<tr><td colspan="9"><a href="#">[关闭-搜索结果]</a></td></tr></table>';
				$(document.body).append(rs_str);
				$("#search_rs").css("left",$("#psearch_key").position().left+10);
				$("#search_rs").css("top",$("#psearch_key").position().top+175);
				$("#search_rs a").click(function(){
					$("#search_rs").remove();
					$("#psearch_key").val("");
				});
				

				$("#search_rs input[type='checkbox']").click(function(){
					if(this.checked){
						var data = eval($("#hidden_data").val());
						var data = data[this.value];
						if(data.g_costprice == "")
						{
							data.g_costprice=0;
						   	
						}
				var datastock = data.storage;
					 var stocktmp = "";
                    if (datastock.length > 0) {
                        stocktmp += '<div class="newstocklist">';
                        for (var s = 0; s < datastock.length; s++) {
                            stocktmp += "<ul><li><font color=\"red\">" + datastock[s].stock + "</font></li><li>" + datastock[s].storage_name + "</li> <li>" + datastock[s].positions + "</li></ul>";
                        }
                        stocktmp += "</div>";
                    }
				$("#purchase_list").append('<tr id="order_list_tr_'+this.value+'"><td><img src=/fuman/images/no.gif class=p_del  style="cursor:pointer" ></td><td><div class="lbt"><a href="#" class="view_img"><img src='+data.imagesurl+' width="60" height="60"></a></div><div class="lbcp"><input  type="hidden"  readonly="true" size="20" name=good_namec[] value="'+data.goods_name+'" /></div></td><td>'+data.goods_name+'</td><td><input readonly="true" name="good_no[]" size="10" type="hidden"  value="'+data.goods_sku+'" /><a href="/product/productlist?other='+data.goods_sku+'" target="_blank">'+data.goods_sku+'</a><input type="hidden" name="goods_id[]" value="'+data.goods_id+'"></td><td><input type="hidden" size="3"  name="buyer[]" value="'+data.businessman+'" /><a href=#  onclick=showDivs('+data.uid+',"'+data.businessman+'","'+data.businessmanline+'") >'+data.businessman+'</td><td><input name="price[]" class="price" size="10" value="'+data.g_costprice+'"/></td><td><input type="number" size="3" name=nums[] class="num" id="skusum" value="1" onkeyup="this.value=this.value.replace(/[^0-9]/g,\'\');" /></td><td><input name="total[]" class="total" size="10" value="'+data.g_costprice+'" readonly="true" /></td><td><span class="stock_num">'+stocktmp+'</span></td><td><span class="stock_num">'+data.skucode+'</span><input name="skucode[]" type="hidden"  size="10" value="'+data.skucode+'" readonly="true" /></td><td><input type="text" class="width200"  name="skumemo[]"   placeholder="交易单号或其他信息"/></td></tr>');		
						
						$(".p_del").click(function(){
							
								$(this.parentNode.parentNode).remove();
							
						});
						$(".price").blur(totalall);
						$(".num").blur(totalall);
						totalall();
					}else{
						$("#purchase_list #order_list_tr_"+this.value).remove();
					}
				});

				$("#btn1").click(function(){
					//$("#search_rs input[type='checkbox']").attr("checked","true");
					$("#search_rs input[type='checkbox']").each(function(){
						$(this).attr("checked","true");
						 $(this).click(); 
						 totalall();
					});
					$("#search_rs").remove();
					$("#psearch_key").val("");
				});
			});
		}
	});////搜索货物事件及返回结果处理--结束

	$(".price").blur(totalall);
	$(".num").blur(totalall);
	$("#takeprice").blur(totalall)
	$("#othermoney").blur(totalall)
	totalall();
});


function totalall(){
	var nums = $(".num");
	var prices = $(".price");
	var  totals = $(".total");

	
	var tmp = 0;
	for(var i=0;i<nums.length;i++){
		totals[i].value = changeTwoDecimal(prices[i].value*nums[i].value);
		tmp += changeTwoDecimal(totals[i].value);
	}
	tmp = changeTwoDecimal(tmp);
	$("#goodsprice").val(tmp);
	var takeprice = $("#takeprice").val();
	var othermoney = $("#othermoney").val();
	var tttt = changeTwoDecimal(parseFloat(tmp)+parseFloat(takeprice));
	tttt=changeTwoDecimal(tttt+parseFloat(othermoney));
	$("#allmoney").val(tttt);
}

function stopDefault(e){
	if(e && e.preventDefault)
		e.preventDefault();
	else
		window.event.returnValue = false;
}
function isEmpty(str){
	var reg = /^\s*$/;
	if(reg.test(str))
		return true;
	else
		return false;
}
function submitup(typeid)
{
	var st=0;
	$("input[id='skusum']").each(function () {
			if ($(this).val() == "" || $(this).val() == 0) {
				alert("数量必须全部填写，不能留空！");
				$(this).focus();
				st = 1;
				return false;
			}

			
		})

	var made_factory = $("#made_factory").val();
	if(made_factory=="")
	{
		alert("请选择供应商");
		return;
	}
	if(made_factory==3){
		var made_way = $("#made_way").val();
		if(made_way==""){
			alert("若供应商为外采购，则采购途径必须选择!");return false;
			return false;
		}

		var platform_message = $("#platform_message").val();
		if(platform_message=="")
		{
			alert("请填写采购编号！");
			return;
		}
	}
	
	
	
	$("#typeid").val(typeid);
	if(st==0){
		$("#goodsForm").submit();
	}
}
function changeTwoDecimal(x)
{
   var f_x = parseFloat(x);
   if (isNaN(f_x))
   {
    //  alert('error');
      
      return false;
   }
   var f_x = Math.round(x*100)/100;
   return f_x;
}
function showDivs(uid,title,url)
{


}
function savegetpay(id)
{
	if (confirm('所有采购信息已经议价完成！\r\n运费、地址均已确认！\r\n'))  
	{
		$.post("/purchase/ajaxbutton", {"op": "saveslistget","id":id,"st":1},
		function(data){
			if(data==201)
			{
				alert('请先填写采购编号！');
				window.location.href = "/purchase/ordermod?id="+id+"";
			}else{
				window.location.href = "/purchase/purchaselist";
			}
	   },"json");

		
		
	}
}

function savegetuser(id,st)
{
	if (confirm('支付款项请按实际流程操作！已付款的采购单才标已支付状态！！'))  
	{
		if($("#getuser"+id).val()!= 0)
		{
			
			$.post("/purchase/ajaxbutton", {"op": "saveslistget","id":id,"st":st},
			  function(data){ 
					if(st == "Y")
					{	
						var postno =1;
						$("#getuserbtn"+id).attr("value","已付");
						$("#spduser"+id).val(postno); 
					}
					else if(st == "N")
					{
						var postno =0;
						 $("#getuserbtn"+id).attr("value","未付");
						$("#postnos"+id).val(postno); 
					 }
					 window.location.href = "/purchase/purchaselist?id="+id;
			   },"json");
				//

			                  
		}
		
	 }
}

function delstocklist(id)
{
	if (confirm('你确认删除吗？'))  
	{
		 $.post("/purchase/ajaxbutton",{ op:"delstocklist",id: id},function (data) {
			 if(data==201){
				 alert("该状态批量订单不能不删除");return false;
			 }else{
				 location.reload();
			 }

		 } );
		//window.location.href = "/purchase/purchaselist";

	}
	
}

function showsavebuy(id,st)
{
	var fk = $("#spduser"+id).val();
	
	$.post("/purchase/ajaxbutton", {"op": "showsavebuy","id":id},
	  function(data){
		if(data==201)
		{
			 window.location.href = "/purchase/purchaselist?id="+id;
			 
		}else{
		  var tmp="";
			 for (var i = 0; i < data.length; i++) {
				tmp += '<tr>'
				tmp += "<td height=58>采购编号:<input type=\"hidden\" value=\""+data[i]+"\" name=\"tborder[]\" id=\"tborder\" ><span><font color=\"#6666FF\">" + data[i] + "</font></span></td><td><input type=\"text\" placeholder=\"快递名称\" name=\"kdname[]\" id=\"kdname\" ></td><td><input placeholder=\"快递号\" type=\"text\" name=\"kdnumber[]\" id=\"kdnumber\" ></td>";
				tmp += "</tr>";
                }
			$("#orderid").val(id);
			$("#showmabangid").html(tmp);
		}
	   },"json");

	$('#showmabangorder').modal('show');
	
}
function editsavebuy(id,st)
{
	$.post("/purchase/ajaxbutton", {"op": "editsavebuy","id":id},
		function(data){
			var tmp="";
			//for (var i = 0; i < data.length; i++) {
				tmp += '<tr>';
				if(data.tborder){
					tmp += "<td>采购编号:<input type=\"text\" value=\""+data.tborder+"\" name=\"tborder\" id=\"tborder\" placeholder=\"采购编号\" style='width:200px;'></td><td><input type=\"text\" placeholder=\"快递名称\" name=\"kdname\" id=\"kdname\" value=\""+data.kdname+"\" ></td><td><input placeholder=\"快递号\" type=\"text\" name=\"kdnumber\" id=\"kdnumber\" value=\""+data.kdnumber+"\" ></td>";
				}else{
					tmp += "<td>采购编号:<input type=\"text\" value=\""+data[0]+"\" name=\"tborder\" id=\"tborder\" placeholder=\"采购编号\" style='width:200px;'></td><td><input type=\"text\" placeholder=\"快递名称\" name=\"kdname\" id=\"kdname\" ></td><td><input placeholder=\"快递号\" type=\"text\" name=\"kdnumber\" id=\"kdnumber\" ></td>";
				}

				tmp += "</tr>";
			//}
			$("#purchaselist_id").val(id);
			$("#editmabangid").html(tmp);
		},"json");

	$('#editmabangorder').modal('show');

}

function atmangban()
{
	var tst=0;
	var inputArray=$("input[id='kdnumber']");//取到所有的input text 并且放到一个数组中 
	inputArray.each(//使用数组的循环函数 循环这个input数组  
         function (){  
             var input =$(this);//循环中的每一个input元素  
            if(input.val()=="")
			{
				 tst =1;
			}
         }  
     )
	 if(tst==1)
	 {
		alert("所有的快递单号必须填写完整!");
		return false;	
	 }
	$("#saveform").submit();
}

function confirmzhijian(id)
{
	 window.location.href="/purchase/check_goods/"+id;	
}

function printbar(cang)
{
	var vote_arrs = document.getElementsByName("idarr[]");
	var idc="";
	for(var j = 0; j < vote_arrs.length; j++)
	{
			if(vote_arrs[j].checked ==1){
	        	idc+= vote_arrs[j].value+",";
			}
	   
    }
	if(idc=='')
	{
		alert('请选择需要打印条码的商品');
		return;
	}
		 window.open('/purchase/ajaxbutton?op=barcode&idc='+idc+'&cang='+cang+'', 'newwindow', 'width='+(window.screen.availWidth-10)+',height='+(window.screen.availHeight-30)+' , top=0, left=0, toolbar=no, menubar=no, scrollbars=auto, resizable=no, location=no, status=no')
}

function saverightadd(id)
{
	if (confirm('当前无入库记录，默认全部按采购数入库。当前有入库记录，只修改状态不入库'))
	{
		var vote_arrs = document.getElementsByName("viceid[]");
		var idc="";
		for(var j = 0; j < vote_arrs.length; j++)
		{
			idc+= vote_arrs[j].value+",";
		}
		var vote_arrs = document.getElementsByName("qualityinNum[]");
		var Nums="";
		for(var j = 0; j < vote_arrs.length; j++)
		{
			Nums+= vote_arrs[j].value+",";
		}


		$.post("/purchase/ajaxbutton", {"op": "saverightadd","id":id,"idc":idc,"Nums":Nums},
		  function(data){
			  if(data==200)
				{
				 window.location.href="/purchase/qualityinspection/"+id;
			  }else if(data==202){
					alert("有未质检完商品，入库数量与质检数量要保持一致！");return false;
			  } else{
				alert('质检失败！');
				return;
			  }
		   },"json");
	}

}

function savefut(id)
{
	//先全部扫描入库
	$.post("/purchase/ajaxbutton", {"op": "noscaninall","id":id},
	  function(data){ 
		for(var i=0;i<data.length;i++)
		{
		   num = parseInt($("#innums"+data[i].id).html(data[i].qualityinNum));
		   // $("#editkg"+data[i].id).val("Y");//打开开关
		}
	   },"json");
		

	
	//保存入库
	$.post("/purchase/ajaxbutton", {"op": "savefullnewadd","id":id},
	  function(data){ 
			if(data==200)
			{
				window.location.href="/purchase/instorage";	
			}
	   },"json");

}

function batchPaystatus()
{
	 var str = selectallpro();
	 if (str != false) {
		$.post("/purchase/ajaxbutton", {"op": "batchPaystatus","id":str},
		  function(data){ 
			window.location.href="/purchase/purchaselist?id="+data;	
		   },"json");
	 }
}

function purchaseData() {

    var str = selectallpro();

    if (str != false) {
        var arr = str.split(',');
        var num = arr.length-1;
		
		var strnum = "";
		for(var i=0;i<arr.length-1;i++)
		{
			if($("#nst"+arr[i]).val()=="")
			{
				var st = 0;
			}else{
				var st = $("#nst"+arr[i]).val();
			}
			if(isNaN(st))
			{
				alert("采购数必须是数字！");
				return;
			}else{
				strnum+=st+",";
			}
		   
		}

        if (confirm("确认将选中的 [ "+num+" ]个商品，生成采购单?")) {

           $("#goods_id_list").val(arr);
		   $("#goods_nums_list").val(strnum);
		   $("#addpurchase").submit();

        }

    }

}